﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZBJF.Warranty.WebProvider.AdminPemission;

namespace ZBJF.Warranty.WebProvider.Filter
{
    #region 管理员权限控制
    public class AuthenticationFilterAttribute : ActionFilterAttribute
    {
        public bool NeedAuthentication { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!NeedAuthentication)
            {
                return;
            }
            //用MVC系统自带的功能 获取当前方法上的特性名称
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(NoNeedAdminAuthory), inherit: true)
                                     || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(NoNeedAdminAuthory), inherit: true);
            if (skipAuthorization || RightHelper.Instance.IsSupperAdmin)
            {
                return;
            }
            var url = string.Empty;
            var controlActionUrl = string.Empty;
            try
            {
                if (filterContext.HttpContext.Request.Url != null)
                    url = filterContext.HttpContext.Request.Url.PathAndQuery;

                var areaName = filterContext.RouteData.DataTokens["area"];
                if (areaName != null && !string.IsNullOrEmpty(areaName.ToString()))
                {
                    controlActionUrl = "/" + areaName;
                }
                //获取触发当前方法的的Action所在的控制器名字
                string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                controlActionUrl += "/" + controllerName;

                //获取触发当前方法（OnActionExecuting）的Action名字（即：哪个Action方法被执行的时候触发的OnActionExecuting(ActionExecutingContext filterContext)）
                string actionName = filterContext.ActionDescriptor.ActionName;
                if (!actionName.Equals("Index", StringComparison.CurrentCultureIgnoreCase))
                {
                    controlActionUrl += "/" + actionName;
                }
            }
            catch
            {

            }
            if (string.IsNullOrEmpty(url.Trim('/')))//表示首页
                return;

            //ajax请求和post请求不需要进行权限验证
            if (!filterContext.Controller.ControllerContext.IsChildAction && !string.IsNullOrEmpty(url) && !(filterContext.HttpContext.Request.IsAjaxRequest() || filterContext.HttpContext.Request.HttpMethod.Equals("post", StringComparison.CurrentCultureIgnoreCase)))
            {
                //设置菜单时，不要加上最后的‘/’,?后面的参数都不需要加
                var pageMenu = RightHelper.Instance.GetAllPageMenuByApplicationType().OrderByDescending(m => string.IsNullOrEmpty(m.PageUrl) ? 0 : m.PageUrl.Length).FirstOrDefault(m => !string.IsNullOrEmpty(m.PageUrl) && (url.ToLower().TrimEnd('/') == m.PageUrl.ToLower().TrimEnd('/') || m.PageUrl.ToLower().TrimEnd('/') == (controlActionUrl.ToLower().TrimEnd('/'))));
                if (pageMenu == null || !RightHelper.Instance.CanViewPage(pageMenu.ID))
                {
                    HttpContext.Current.Response.Redirect("/Login/NoAuthory");
                }
                else
                {
                    var hasNoRightOperationActionList = RightHelper.Instance.GetCurrentUserNoRightActionCode(pageMenu.ID)
                           .Aggregate(string.Empty, (c, d) => c + d + "-R,")
                           .Trim(',');
                    filterContext.Controller.ViewBag.HasNoRightOperationActionList = hasNoRightOperationActionList;

                    //判断当前用户是否有当前页面的访问权限（只要有当前页面一个按钮的权限则断定为有权限）
                    if (RightHelper.Instance.GetCurrentUserHasRightActionCode(pageMenu.ID).Count < 0)
                    {
                        filterContext.Result = new JsonResult()
                        {
                            Data = new { success = false, message = "您暂无权限操作" }
                        };
                    }
                }
            }

            base.OnActionExecuting(filterContext);
        }
    }
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class NoNeedAdminAuthory : Attribute
    {
    }

    /// <summary>
    /// 表示当前Action请求为一个具体的功能页面
    /// </summary>
    public class AdminActionAttribute : Attribute
    {
        /// <summary>
        /// 页面请求路径
        /// </summary>
        public string ActionUrl { get; set; }
        /// <summary>
        /// 页面操作代码
        /// </summary>
        public string ActionCode { get; set; }
        /// <summary>
        /// 页面返回类型（0：返回页面，1返回json格式）
        /// </summary>
        public int ActionResultType { get; set; }
    }
    #endregion
}